#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =================================================
# @File    : es_index_script
# @IDE     : PyCharm
# @Author  : Liu Xian Gui
# @Date    : 2024/5/15 22:21
# @Describe: 
# ==================================================
import datetime
from elasticsearch import Elasticsearch
import requests

# Elasticsearch配置
es = Elasticsearch(["localhost:9200"])

# 计算最近3分钟的时间范围，查询当前3分钟的数据
current_time = datetime.datetime.utcnow()
one_minute_ago = current_time - datetime.timedelta(minutes=3)

# 构建Elasticsearch查询语句
query = {
    "query": {
        "bool": {
            "filter": [
                {"range": {"@timestamp": {"gte": one_minute_ago.isoformat()}}},
                {"match_phrase": {"rest": "- error2589"}}
            ]
        }
    },
    "sort": [{"@timestamp": {"order": "desc"}}],
    "size": 1
}

# 在索引中执行查询
index_name = "applog"
result = es.search(index=index_name, body=query)

# 如果有符合条件的结果
if result["hits"]["total"]["value"] > 0:
    # 获取最近一次的内容
    recent_error = result["hits"]["hits"][0]["_source"]["rest"]

    # 发送钉钉报警
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=？？"
    headers = {"Content-Type": "application/json"}
    data = {"msgtype": "text", "text": {"content": f"发生报警：{recent_error}"}}

    response = requests.post(webhook_url, json=data, headers=headers)

    if response.status_code == 200:
        print("报警已发送")
    else:
        print("报警发送失败")
else:
    print("最近1分钟内没有包含名为error2589的内容")

